package com.lingnan.blog.controller;

import com.lingnan.blog.entity.Friend;
import com.lingnan.blog.entity.User;
import com.lingnan.blog.service.*;
import com.lingnan.blog.utils.ShiroUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
public class PagesController {
    private final String USER_ROLE = "博主";

    @Autowired
    private UserService userService;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private TagsService tagsService;
    @Autowired
    private CollectService collectService;
    @Autowired
    private FriendService friendService;
    @Autowired
    private TimeTravelService timeTravelService;

    @Autowired
    HttpSession session;

    /**
     * 登录页面
     *
     * @param msg
     * @param model
     * @return
     */
    @GetMapping("/login")
    public String login(@ModelAttribute("msg") String msg, Model model) {
        model.addAttribute("msg", msg);
        return "login.html";
    }

    /**
     * 注册页面
     *
     * @param msg
     * @param model
     * @return
     */
    @GetMapping("/register")
    public String register(@ModelAttribute("msg") String msg, Model model) {
        model.addAttribute("msg", msg);
        return "register.html";
    }

    /**
     * 主页
     *
     * @param model
     * @param session
     * @return
     */
    @GetMapping(value = {"/", "/index"})
    public String toIndex(Model model, HttpSession session) {
        try {
            //*********主页面*********
            session.setAttribute("loginUser", ShiroUtils.getUser());
            //获取博主信息
            User blogger = userService.findByUserRole(USER_ROLE);
            //存入model
            model.addAttribute("blogger", blogger);
            //查询所有文章
            model.addAttribute("articleList", articleService.findAll());
            //获取标签库
            model.addAttribute("tagList", tagsService.findByAll());
            //跳转到主页
            return "index.html";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 顶部栏（“面试那些事”）
     *
     * @param model
     * @return
     */
    @GetMapping("/interview")
    public String toInterview(Model model) {
        try {
            //*********面试那些事页面*********
            //获取关于面试的文章
            model.addAttribute("interviewList", articleService.findInterviewArticle());
            //获取标签库
            model.addAttribute("tagList", tagsService.findByAll());
            return "interview.html";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 顶部栏（“时间旅行”）
     *
     * @param model
     * @return
     */
    @GetMapping("/timeTravel")
    public String list(Model model) {
        model.addAttribute("list", timeTravelService.findAll());
        return "timeTravel.html";
    }

    /**
     * 博客动态详情页面
     *
     * @param uid
     * @param model
     * @param msg
     * @return
     */
    @GetMapping("/dynamic/{uid}")
    public String toDynamic(@PathVariable("uid") Integer uid, Model model, @ModelAttribute("msg") String msg) {
        try {
            //*********我的动态页面*********
            //返回用户和文章数据
            model.addAttribute("user", userService.findArticlesById(uid));

            //查询当前用户的文章收藏总数
            model.addAttribute("collects", collectService.findCountByUid(uid));

            //我关注的
            model.addAttribute("myAttention", friendService.findCountByUid(uid));
            //关注我的
            model.addAttribute("attentionMy", friendService.findCountByFid(uid));

            //返回信息
            model.addAttribute("msg", msg);
            return "dynamic.html";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/mydata/{id}")
    public String myData(@PathVariable("id") Integer id, @ModelAttribute("msg") String msg, Model model) {
        //查询用户
        model.addAttribute("user",userService.findById(id));
        //保存更新信息
        model.addAttribute("msg", msg);
        return "mydata.html";
    }

    /**
     * 用户关注
     *
     * @param fid
     * @param model
     * @return
     */
    @GetMapping("/friend/{fid}")
    public String saveFriendInfo(@PathVariable("fid") Integer fid, RedirectAttributes model) {
        //用户关注作者
        User loginUser = ShiroUtils.getUser();
        if (loginUser != null) {
            Friend friend = friendService.findByUIdAndFId(loginUser.getId(), fid);
            //根据用户id和被关注人的id查询当前用户是否关注过此人
            if (StringUtils.isEmpty(friend)) {
                //为空，没关注
                //用户登录了才能关注对方
                friendService.saveSelective(new Friend(null, loginUser.getId(), fid));
                model.addFlashAttribute("msg", "关注成功");
            } else {
                model.addFlashAttribute("msg", "你已经关注了对方");
            }
        }
        //返回作者页面
        return "redirect:/dynamic/" + fid;
    }

    /**
     * 文章发布页面
     *
     * @param model
     * @return
     */
    @GetMapping("/issue")
    public String toIssue(Model model) {
        try {
            //*********文章发布页面*********
            //获取标签库
            model.addAttribute("tagList", tagsService.findByAll());
            return "issue.html";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 文章编辑页面
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/article/edit/{id}")
    public String toEditArticle(@PathVariable("id") Integer id, Model model) {
        try {
            //*********文章编辑*********
            //查询文章返回数据
            model.addAttribute("article", articleService.findById(id));
            //获取所有标签库
            model.addAttribute("tagList", tagsService.findByAll());
            return "issue.html";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 文章详情页面
     *
     * @param id
     * @param msg
     * @param model
     * @return
     */
    @GetMapping(value = {"/article/{id}", "/interview/{id}"})
    public String toArtie(@PathVariable("id") int id, @ModelAttribute("msg") String msg, Model model) {
        try {
            //*********文章详情页面*********
            User loginUser = ShiroUtils.getUser();
            //更新文章浏览记录
            articleService.updateView(id, loginUser);

            ///查询当前登录的用户是否收藏过当前文章
            if (loginUser != null) {
                collectService.findByUidAndAid(loginUser.getId(), id);
                model.addAttribute("collect", collectService.findByUidAndAid(loginUser.getId(), id));
            }

            //文章id查找文章和文章作者
            model.addAttribute("article", articleService.findById(id));
            //获取当前文章的评论数
            model.addAttribute("commentList", commentService.findAllByAId(id));
            //返回消息
            model.addAttribute("msg", msg);
            return "article.html";
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 标签页面
     *
     * @param tag
     * @param model
     * @return
     */
    @GetMapping("/label/{tag}")
    public String toLabel(@PathVariable("tag") String tag, Model model) {
        //返回标签名字
        model.addAttribute("tag", tag);
        //查询出当前标签id的所有文章
        model.addAttribute("articleList", articleService.findByTag(tag));
        return "label.html";
    }


}
